package com.whz.gateway.filter;

import com.whz.gateway.common.constants.FilterOrder;
import com.whz.gateway.common.util.HeaderUtils;
import com.whz.gateway.configure.access.admin.AdminAccessProperties;
import com.whz.gateway.limit.GatewayRemoteIpResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * 权限控制
 *
 * @author whz
 */
@Slf4j
@Component
public class ApiBizFilter extends AbstractGlobalFilter implements Ordered {

    @Resource
    private GatewaySwitcher gatewaySwitcher;

    @Resource(name = GatewayRemoteIpResolver.BEAN_NAME)
    private GatewayRemoteIpResolver gatewayRemoteIpResolver;

    @Resource
    private AdminAccessProperties adminAccessProperties;

    @Override
    protected boolean shouldFilter(ServerWebExchange exchange) {
        HeaderUtils.TokenInfo token = HeaderUtils.getTokenValue(exchange);
        // 权控开关
        boolean should = token != null && token.getBiz() == HeaderUtils.TokenBiz.API;
        if (should) {
            log.info("开始处理API业务,token:{}", token);
        }
        return should;
    }

    @Override
    protected Mono<Void> apply(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 从 HeaderUtils.currentUserDetails(exchange) 中查询openid中的clientId
        String clientId = HeaderUtils.currentClient(exchange);
        log.info("Api login,current clientId:{}", clientId);
        if (StringUtils.isEmpty(clientId)) {
            log.error("用户数据中没有clientId, token:{}", HeaderUtils.getTokenValue(exchange));
        }
        /*
         *  TODO 下面按照clientId查询业务数据,处理业务规则
         *   例如 付费后,API的查询次数,校验/统计/到期
         */
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return FilterOrder.API_BIZ_ORDER;
    }
}